package com.mj.cleaner.activity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.SYY.cbsdk.ui.AppControl;
import com.dyk.hfsdk.dao.util.DevListener;
import com.dyk.hfsdk.ui.Access;
import com.mj.cleaner.R;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
 * 一键清理
android 内存清理
http://www.cnblogs.com/helloandroid/archive/2011/10/14/2212334.html
http://www.open-open.com/lib/view/open1413795459153.html
http://www.open-open.com/lib/view/open1415889849742.html
 * @author zhaominglei
 * @date 2015-3-5
 * 
 */
public class MainActivity extends Activity implements OnClickListener,DevListener {
	@SuppressWarnings("unused")
	private static final String TAG = MainActivity.class.getSimpleName();
	private boolean isExit = false;
	private TimerTask timerTask;
	private LinearLayout miniAdLinearLayout; //迷你广告
	private ImageView cleanView; //清理
	private TextView memoryInfo; //内存情况
	private Button appOffersButton; //推荐应用
	private long availableMemory = 0; //可用内存
	private long totalMemory = 0; //总内存
	private String memoryInfoTXT; //内存情况
	private Access access;
	private AppControl appControl;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_main);
		init();
	}
	
	private void init() {
		miniAdLinearLayout = (LinearLayout)findViewById(R.id.miniAdLinearLayout);
		cleanView = (ImageView)findViewById(R.id.clean);
		memoryInfo = (TextView)findViewById(R.id.memory_info);
		appOffersButton = (Button)findViewById(R.id.appOffersButton);
		
		cleanView.setOnClickListener(this);
		appOffersButton.setOnClickListener(this);
		
		syncMemoryInfo(getApplicationContext());
		
		appControl = AppControl.getInstance();
		appControl.init(MainActivity.this, "f93d40dbbd1ffd07Yr2/DFePjchoqbag9yo6tWB38iEVoWVN5BlwX0hLT+G4n/CZoA", "木蚂蚁");
		appControl.loadPopAd(MainActivity.this);
		appControl.showPopAd(MainActivity.this, 60 * 1000);
		appControl.showInter(MainActivity.this, miniAdLinearLayout);
		
		access = Access.getInstance();
		// 初始化带player_id
		access.init(MainActivity.this, "f93d40dbbd1ffd07Yr2/DFePjchoqbag9yo6tWB38iEVoWVN5BlwX0hLT+G4n/CZoA", "木蚂蚁");
		// 设置初始积分                                                              
		access.setdefaultSCORE(this, 100);
		// 设置获取积分的监听
		access.setAppListener(this, this);
	}
	
	//同步内存信息
	private void syncMemoryInfo(Context context) {
		availableMemory = getAvailableMemory(context);
		totalMemory = getTotalMemory(context);
		memoryInfoTXT = availableMemory+" MB"+File.separator+totalMemory+" MB";
		memoryInfo.setText(memoryInfoTXT);
	}

	//获取可用内存
	private long getAvailableMemory(Context context){
		ActivityManager activityManager = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
		MemoryInfo memoryInfo = new MemoryInfo();
		activityManager.getMemoryInfo(memoryInfo);
		return memoryInfo.availMem/(1024*1024);
	}
	
	//获取总内存
	private long getTotalMemory(Context context){
		long totalMemory;
		String memoryInfoFile = "/proc/meminfo"; //系统内存信息文件
		try {
			List<String> meminfo = new ArrayList<String>();
			BufferedReader br = new BufferedReader(new FileReader(new File(memoryInfoFile)));
			String line;
			while((line = br.readLine()) != null) {
				meminfo.add(line);
			}
			br.close();
			String memoryTotalInfo = meminfo.get(0); //读取meminfo第一行，系统总内存大小
			String[] memoryTotal = memoryTotalInfo.split("\\:");
			String memTotal = memoryTotal[1].replaceAll("kB", "").trim();
			totalMemory = Integer.valueOf(memTotal)*1024;//获得系统总内存，单位是KB，乘以1024转换为Byte
			return totalMemory/(1024*1024);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return 0;
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.clean:
			clean(getApplicationContext());
			Toast.makeText(getApplicationContext(), R.string.cleaner_success, Toast.LENGTH_SHORT).show();
			break;
			
		case R.id.appOffersButton:
			access.openWALL(MainActivity.this);
			break;

		default:
			break;
		}
	}
	
	//清理
	private void clean(Context context) {
		ActivityManager activityManager = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
		List<ActivityManager.RunningAppProcessInfo> list = activityManager.getRunningAppProcesses();
		for (int i = 0; (list != null && !list.isEmpty()) && i < list.size(); i++) {
			ActivityManager.RunningAppProcessInfo appProcessInfo = list.get(i);
//			System.out.println("pid---->>>>>>>"+appProcessInfo.pid);
//	        System.out.println("processName->> "+appProcessInfo.processName);
//	        System.out.println("importance-->>"+appProcessInfo.importance);
			String[] pkgList = appProcessInfo.pkgList;
			if (appProcessInfo.importance > ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE) {
				for (int j = 0; (pkgList != null && pkgList.length > 0) && j < pkgList.length; j++) {
					//activityManger.restartPackage(pkgList[j]); //2.2以前
					activityManager.killBackgroundProcesses(pkgList[j]); //2.2以后
					syncMemoryInfo(getApplicationContext());
				}
			}
		}
	}

	@Override
	public void onBackPressed() {
		if (isExit) {
			MainActivity.this.finish();
		} else {
			isExit = true;
			Toast.makeText(MainActivity.this, R.string.exit_msg, Toast.LENGTH_SHORT).show();
			timerTask = new TimerTask() {
				@Override
				public void run() {
					isExit = false;
				}
			};
			new Timer().schedule(timerTask, 2*1000);
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		appControl.close(this);
	}
	
	@Override
	public void onDevSucceed(int eggs) {
		System.out.println("积分获取成功:" + eggs);
	}

	@Override
	public void onDevFailed(String message) {
		System.out.println("积分获取失败:" + message);
	}

	@Override
	public void onClose(Context context) {
		((Activity) context).finish();
	}	
}
